<style lang="scss"></style>

<template>
  <el-config-provider :locale="locale">
    <RouterView></RouterView>
  </el-config-provider>
  <ThemePicker />
  <audio preload="none" ref="newOrderPlayer" src="@/assets/file/newOrder.mp3" />
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import ConfigProvider from '@/components/ConfigProvider.vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import ThemePicker from '@/components/ThemePicker/index.vue'
import mqtt from 'mqtt'
import { ElNotification } from 'element-plus'
import env from '@/utils/env'
import { watch } from 'vue'
import { useRoute } from 'vue-router'

const locale = zhCn
const store = useStore()
const router = useRouter()

// 定义响应式数据
const newOrderPlayer = ref<HTMLAudioElement | null>(null)
const notifyFlag = ref(false)
const messageData = ref<string | null>(null)
const notify = ref<any>(null)
let mqttClient: mqtt.MqttClient | null = null

// 页面等比例缩放的方法
const bodyScale = () => {
  const deviceWidth = document.documentElement.clientWidth //获取当前分辨率下的可是区域宽度
  const scale = deviceWidth / 1920 // 分母——设计稿的尺寸
  document.documentElement.style.zoom = String(scale) //放大缩小相应倍数
}

// mqtt连接
const openMqtt = () => {
  const clientId = 'pc_' + store.state.user.id + new Date().getTime()
  const clientTopic = 'pc_user/' + store.state.user.id
  // let serviceTopic = 'topic/sport_server_test'
  mqttClient = mqtt.connect(env.VITE_APP_MQTT_API as string, {
    clientId: clientId,
    username: env.VITE_APP_MQTT_USERNAME || 'admin',
    password: env.VITE_APP_MQTT_PASSWORD || 'shenshi@123',
    keepalive: 20, // 心跳时间
    clean: true, // 清除会话
    connectTimeout: 30 * 1000, // 连接超时时间 ms
    reconnectPeriod: 2000, // 重连时间间隔 ms
    // cleanSession: false, // 启用持久会话
    // will: {topic: serviceTopic, payload: '{"msgType": "999","payloadName": "mqtt遗嘱消息连接断开"}', qos: 2, retain: false},// TODO 遗嘱消息 保留 暂不添加
  })
  mqttClient.on('connect', () => {
    console.log('mqtt 已经连接成功')
    mqttClient!.subscribe(clientTopic, { qos: 2 }, (data) => {
      console.log('mqtt ' + clientTopic + ' 订阅成功')
      // TODO 先保留 连接后发送消息到服务端
      // client.publish(serviceTopic, '{"msgType": "1","payloadName": "mqtt连接成功"}', {qos: 2}, error => {
      //   if (error) {
      //     console.log('mqtt 发送消息失败', error)
      //   } else {
      //     console.log('mqtt 发送消息成功')
      //   }
      // })
    })
  })
  mqttClient.on('message', (topic, data) => {
    console.log('mqtt 收到' + topic + '的消息')
    messageData.value = data.toString()
    newOrderDialog()
  })
  mqttClient.on('reconnect', () => {
    console.log('mqtt 重新连接')
  })
  mqttClient.on('offline', () => {
    console.log('mqtt 超时')
  })
  mqttClient.on('error', (error) => {
    console.log('mqtt 异常')
    console.log(error)
  })
  mqttClient.on('close', () => {
    console.log('mqtt 关闭')
  })
}

// 新订单消息弹框
const newOrderDialog = () => {
  if (!notifyFlag.value) {
    // 播放新的订单
    speechNewOrder()
    notifyFlag.value = true
    notify.value = ElNotification({
      dangerouslyUseHTMLString: true,
      position: 'bottom-right',
      showClose: false,
      duration: 0,
      message:
        '<div class="message-container"><i style="color: rgba(252, 162, 183, 1);font-size: 5rem;" class="el-icon-message-solid"></i></div>' +
        '<br/>' +
        '<div class="message-container"><span style="font-size: 1.5rem;color: #383838">您有新的订单！</span></div>' +
        '<br/>' +
        '<div class="message-btn">' +
        '<div style="width: 50%;text-align: center;"><button class="btn-cancel">忽略</button></div>' +
        '<div style="width: 50%;text-align: center;"><button class="btn-handle">马上处理</button></div>' +
        '</div>',
      onClose: () => {
        notifyFlag.value = false
      },
    })
    // 确保元素已渲染后再添加事件监听器
    nextTick(() => {
      if (notify.value && notify.value.$el) {
        const buttons = notify.value.$el.querySelectorAll('button')
        if (buttons.length >= 2) {
          buttons[0].addEventListener('click', handleCancelClick)
          buttons[1].addEventListener('click', handleOrder)
        }
      }
    })
  }
}

// 播放新订单音频
const speechNewOrder = () => {
  if (newOrderPlayer.value) {
    newOrderPlayer.value.load()
    newOrderPlayer.value.currentTime = 0
    newOrderPlayer.value.play().catch((e) => console.log('音频播放失败:', e))
  }
}

// 忽略消息
const handleCancelClick = () => {
  if (notify.value) {
    notify.value.close()
  }
}

// 消息-马上处理
const handleOrder = () => {
  try {
    const messageObj = JSON.parse(messageData.value as string)
    if (messageObj && messageObj.content) {
      const messageCont = messageObj.content
      router.push({
        path: '/order/detail',
        query: { id: messageCont.orderId },
      })
      handleCancelClick()
    }
  } catch (e) {
    console.error('解析消息数据失败:', e)
  }
}

// 监听路由变化

const route = useRoute()

watch(
  () => route.path,
  (newPath, oldPath) => {
    if (newPath !== '/login') {
      // mqtt连接
      // TODO mqtt 连接
      openMqtt()
    }
  },
)

onMounted(() => {
  // 监听页面的窗口的变化，每次窗口变化调用等比例缩放方法
  // window.addEventListener("resize", bodyScale, false);
})

onBeforeUnmount(() => {
  // 清理 MQTT 客户端连接
  if (mqttClient) {
    mqttClient.end()
  }

  // 清理通知事件监听器
  if (notify.value && notify.value.$el) {
    const buttons = notify.value.$el.querySelectorAll('button')
    if (buttons.length >= 2) {
      buttons[0].removeEventListener('click', handleCancelClick)
      buttons[1].removeEventListener('click', handleOrder)
    }
  }
})
</script>
<style scoped>
#app .theme-picker {
  display: none;
}
</style>
<style>
.el-notification {
  background-color: #fff;
  padding: 15px 15px 20px;
}

.el-notification__title {
  color: #383838 !important;
}

.el-notification__content {
  color: #383838 !important;
}

.el-notification__group {
  width: 100% !important;
}

.message-container {
  display: flex;
  align-items: center;
  justify-content: center;
}

.message-btn {
  display: flex;
}

.btn-cancel {
  width: 121px;
  padding: 10px;
  border-radius: 10px;
  background-color: #e5e5e5;
  color: #383838;
  border: none;
  transition: background-color 0.3s;
  cursor: pointer;
}

.btn-handle {
  width: 121px;
  padding: 10px;
  border-radius: 10px;
  background-color: #2a82e4;
  border: none;
  color: white;
  transition: background-color 0.3s;
  cursor: pointer;
}

.btn-cancel:active {
  background-color: #bdbdbd;
}

.btn-handle:active {
  background-color: #bdbdbd;
}
input[aria-hidden='true'] {
  display: none;
}
</style>
